package com.ikingtech.framework.sdk.cmd;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.IOException;

/**
 * @author tie yan
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CmdTracerManager {

    private static final ThreadLocal<File> CMD_CONTEXT = new ThreadLocal<>();

    public static void initLogDir() throws IOException {
        File logDir = new File("cmd-log/");
        if (!logDir.exists()) {
            boolean createLogDirResult = logDir.mkdir();
            if (!createLogDirResult) {
                throw new IOException("create log dir fail");
            }
        }
    }

    public static void start(String outputFileName) {
        CMD_CONTEXT.remove();
        File file = new File("cmd-log/" + outputFileName + ".log");
        if (file.exists()) {
            CMD_CONTEXT.set(file);
        } else {
            boolean newFileResult;
            try {
                newFileResult = file.createNewFile();
            } catch (Exception e) {
                throw new FrameworkException("创建安装日志文件失败！");
            }
            if (!newFileResult) {
                throw new FrameworkException("创建安装日志文件失败！");
            }
        }
        CMD_CONTEXT.set(file);
    }

    public static File get() {
        return CMD_CONTEXT.get();
    }

    public static void clear() {
        CMD_CONTEXT.remove();
    }
}
